package com.example.admin.utils;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 响应服务工具类
 */
@Component
public class JsonResponseService {

    // 默认的错误消息和代码
    private static final String DEFAULT_FAIL_MESSAGE = "操作失败";
    private static final int DEFAULT_FAIL_CODE = HttpStatus.BAD_REQUEST.value();

    // 默认的成功消息
    private static final String DEFAULT_SUCCESS_MESSAGE = "ok";

    // 重载的 fail 方法，只有消息和代码参数
    public ResponseEntity<Map<String, Object>> fail(String msg, int code) {
        return fail(msg, code, null, null);
    }

    // 重载的 fail 方法，只有消息参数
    public ResponseEntity<Map<String, Object>> fail(String msg) {
        return fail(msg, DEFAULT_FAIL_CODE, null, null);
    }

    // 重载的 fail 方法，没有参数
    public ResponseEntity<Map<String, Object>> fail() {
        return fail(DEFAULT_FAIL_MESSAGE, DEFAULT_FAIL_CODE, null, null);
    }

    // 完整的 fail 方法
    public ResponseEntity<Map<String, Object>> fail(String msg, int code, HttpHeaders headers, Object data) {
        if (headers == null) {
            headers = new HttpHeaders();
        }
        if (data == null) {
            data = new HashMap<>();
        }

        Map<String, Object> result = new HashMap<>();
        result.put("code", code);
        result.put("msg", msg);
        result.put("data", data);

        return new ResponseEntity<>(result, headers, HttpStatus.BAD_REQUEST);
    }

    // 重载的 success 方法，只有数据参数
    public ResponseEntity<Map<String, Object>> success(Object data) {
        return success(data, DEFAULT_SUCCESS_MESSAGE, null);
    }

    // 重载的 success 方法，只有消息参数
    public ResponseEntity<Map<String, Object>> success(String msg) {
        return success(null, msg, null);
    }

    // 重载的 success 方法，只有数据和消息参数
    public ResponseEntity<Map<String, Object>> success(Object data, String msg) {
        return success(data, msg, null);
    }

    // 完整的 success 方法
    public ResponseEntity<Map<String, Object>> success(Object data, String msg, HttpHeaders headers) {
        if (headers == null) {
            headers = new HttpHeaders();
        }
        if (data == null) {
            data = new HashMap<>();
        } else if (!(data instanceof Map)) {
            Object finalData = data;
//            data = new HashMap<String, Object>() {{
//                put("info", finalData);
//            }};
        }

        Map<String, Object> result = new HashMap<>();
        result.put("code", 1);
        result.put("msg", msg != null ? msg : DEFAULT_SUCCESS_MESSAGE);
        result.put("data", data);

        return new ResponseEntity<>(result, headers, HttpStatus.OK);
    }
}
